package com.school.basic.service.impl;

import com.school.basic.entity.ClassInfo;
import com.school.basic.entity.StudentInfo;
import com.school.basic.repository.ClassInfoRepository;
import com.school.basic.repository.StudentInfoRepository;
import com.school.basic.repository.TeacherInfoRepository;
import com.school.basic.service.StudentInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class StudentInfoServiceImp implements StudentInfoService {
    @Autowired
    StudentInfoRepository studentInfoRepository;
    @Autowired
    ClassInfoRepository classInfoRepository;
    @Autowired
    TeacherInfoRepository teacherInfoRepository;

    /**
     * 增加
     * @param studentInfo
     * @return
     */
    @Override
    public StudentInfo addStudentInfo(StudentInfo studentInfo) {
        studentInfo.setCreateDate(new Date());
        studentInfo.setUpdateDate(new Date());
        StudentInfo result = studentInfoRepository.save(studentInfo);
        Integer classId = studentInfo.getClassId();
        if(classId != null){
            ClassInfo classInfo = classInfoRepository.findById(classId).get();
            String total = classInfo.getTotal();
            if(!StringUtils.isEmpty(total)){
                total = total + "," + result.getId().toString();
            } else{
                total = result.getId().toString();
            }
            classInfo.setTotal(total);
            classInfoRepository.saveAndFlush(classInfo);
        }
        return result;
    }

    /**
     * 查询所有
     * @param
     */
    @Override
    public List<StudentInfo> findAll() {
        return studentInfoRepository.findAll();
    }

    /**
     * 修改
     * @param studentInfo
     * @return
     */
    @Override
    public StudentInfo updateStudentInfo(StudentInfo studentInfo) {
        studentInfo.setUpdateDate(new Date());
        StudentInfo result = studentInfoRepository.findById(studentInfo.getId()).get();
        Integer classId = result.getClassId();
        // 班级不同，，删除原班级的人数，增加新班级的人数；班级相同，不做操作
        if(classId != studentInfo.getClassId()){
            // 增加新班级的人数
            ClassInfo classInfo = classInfoRepository.findById(classId).get();
            String total = classInfo.getTotal();
            if(!StringUtils.isEmpty(total)){
                total = total + "," + result.getId().toString();
            } else{
                total = result.getId().toString();
            }
            classInfo.setTotal(total);
            classInfoRepository.saveAndFlush(classInfo);
            // 删除原班级的人数
            ClassInfo classInfoId = classInfoRepository.findById(studentInfo.getClassId()).get();
            String arrTotal = classInfo.getTotal();
            List<String> totalList = new ArrayList<>();
            String[] split = arrTotal.split(",");
            for(String s : split){
                if(!s.equals(studentInfo.getId())){
                    totalList.add(s);
                }
            }
            classInfoId.setTotal(totalList.toString());
            classInfoRepository.saveAndFlush(classInfoId);
        }

        return studentInfoRepository.saveAndFlush(studentInfo);
    }

    /**
     * 学生状态变更
     * @param id,status
     */
    @Override
    public void updateStatus(String id,Integer status) {
        StudentInfo studentInfo;
        try {
            studentInfo = studentInfoRepository.findById(Integer.valueOf(id)).get();
            studentInfo.setStatus(status);
            studentInfoRepository.saveAndFlush(studentInfo);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查看详情
     * @param id
     */
    @Override
    public StudentInfo getDetailsById(String id) {
        return studentInfoRepository.findById(Integer.valueOf(id)).get();
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void deleteStudentInfo(String id) {
        StudentInfo studentInfo;
        try {
            studentInfo = studentInfoRepository.findById(Integer.valueOf(id)).get();
            studentInfoRepository.delete(studentInfo);
            Integer classId = studentInfo.getClassId();
            ClassInfo classInfo = classInfoRepository.findById(classId).get();
            String total = classInfo.getTotal();
            List<String> totalList = new ArrayList<>();
            String[] split = total.split(",");
            for(String s : split){
                if(!s.equals(id)){
                    totalList.add(s);
                }
            }
            classInfo.setTotal(totalList.toString());
            classInfoRepository.saveAndFlush(classInfo);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    /**
     * 批量删除
     * @param idList
     */
    @Override
    public void deleteStudentInfoList(String idList) {
        try {
            String[] split = idList.split(",");
            for (String s : split) {
                StudentInfo studentInfo = studentInfoRepository.findById(Integer.valueOf(s)).get();
                studentInfoRepository.delete(studentInfo);
                Integer classId = studentInfo.getClassId();
                ClassInfo classInfo = classInfoRepository.findById(classId).get();
                String total = classInfo.getTotal();
                List<String> totalList = new ArrayList<>();
                String[] arrTotal = total.split(",");
                for(String array : arrTotal){
                    if(!array.equals(s)){
                        totalList.add(array);
                    }
                }
                classInfo.setTotal(totalList.toString());
                classInfoRepository.saveAndFlush(classInfo);
            }
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据条件分页查询
     * @param studentInfo,page,size
     */
    @Override
    public Page<StudentInfo> specificPageQueryStudentInfoList(StudentInfo studentInfo,int page, int size) {
        Specification querySpecification = new Specification() {
            @Override
            public Predicate toPredicate(Root root, CriteriaQuery criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if(studentInfo != null)
                {
                    Integer schoolId = studentInfo.getSchoolId();
                    Integer grade = studentInfo.getGrade();
                    Integer classId = studentInfo.getClassId();
                    Integer status = studentInfo.getStatus();
                    String name = studentInfo.getName();
                    if(schoolId != null){
                        predicates.add(criteriaBuilder.equal(root.get("schoolId").as(Integer.class),schoolId));
                    }
                    if (grade != null)
                    {
                        predicates.add(criteriaBuilder.equal(root.get("grade").as(Integer.class),grade));
                    }
                    if (classId != null)
                    {
                        predicates.add(criteriaBuilder.equal(root.get("classId").as(Integer.class),classId));
                    }
                    if (status != null)
                    {
                        predicates.add(criteriaBuilder.equal(root.get("status").as(Integer.class),status));
                    }
                    if (!StringUtils.isEmpty(name))
                    {
                        predicates.add(criteriaBuilder.like(root.get("name").as(String.class),'%' + name + '%'));
                    }
                }
                return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        List<StudentInfo> studentInfoList = studentInfoRepository.findAll(querySpecification);
        for(int i = 0; i < studentInfoList.size(); i++){
            Integer classId = studentInfoList.get(i).getClassId();
            if(classId != null){
                ClassInfo classInfo = classInfoRepository.findById(classId).get();
                if(classInfo != null){
                    if(!StringUtils.isEmpty(classInfo.getClassName())){
                        studentInfoList.get(i).setClassName(classInfo.getClassName());
                    }
                    if(!StringUtils.isEmpty(classInfo.getHeadMasterName())){
                        studentInfoList.get(i).setHeadMasterName(classInfo.getHeadMasterName());
                    }
                }
            }
        }
        PageRequest pageRequest = PageRequest.of(page - 1, size, Sort.by(Sort.Direction.DESC,"updateDate"));
        // 当前页第一条数据在List中的位置
        int start = (int)pageRequest.getOffset();
        // 当前页最后一条数据在List中的位置
        int end = (start + pageRequest.getPageSize()) > studentInfoList.size() ? studentInfoList.size() : ( start + pageRequest.getPageSize());
        // 配置分页数据
        return new PageImpl<StudentInfo>(studentInfoList.subList(start, end), pageRequest, studentInfoList.size());
    }

    @Override
    public StudentInfo findStudentByAccountAndPassword(Integer account, String password) {
        StudentInfo studentInfo = new StudentInfo();
        studentInfo.setAccount(account);
        studentInfo.setPassword(password);
        Optional<StudentInfo> one = studentInfoRepository.findOne(Example.of(studentInfo));
        studentInfo = null;
        return one.orElse(null);
    }
}
